/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.util;

import io.netty.buffer.ByteBuf;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * @author
 * @apiNote 基础工具类
 * @date 2022/4/27 9:33
 */
public  final class CommonUtil {

    private CommonUtil() {
        throw new IllegalAccessError("can not use constructor about static class");
    }

    /**
     * 计算checkSum
     */
    public static int calCheckSum(ByteBuf byteBuf, int length) {
        if(length <=0) {
            throw new IllegalArgumentException("length <= 0");
        }
        byte checkSum = 0;
        length = Math.min(length, byteBuf.writerIndex());
        for(int i = 0; i<length; i++) {
            checkSum += byteBuf.getByte(i);
        }

        return 0x00ff & checkSum;
    }

    /**
     * 计算checkSum
     */
    public static int calCheckSum(byte[] bytes) {
        if(null == bytes) {
            throw new IllegalArgumentException("byte is null.");
        }
        byte checkSum = 0;
        for(int i =0; i<bytes.length; i++) {
            checkSum += bytes[i];
        }
        return 0x00ff & checkSum;
    }

    /**
     * 获取当前日期
     */
    public static String nowTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateToStrFmt = DateTimeFormatter.ofPattern("yyyyMMdd hh:mm:ss");
        return dateToStrFmt.format(now);
    }
}